import React, { useState } from 'react';
import { View, Text, TextInput, Image, StyleSheet, TouchableOpacity, Alert } from 'react-native';
import { useRoute, useNavigation } from '@react-navigation/native';
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import axios from 'axios';

// 定义用户数据的类型
interface UserData {
  _id: string;
  img: string;
  name: string;
  profile: string;
  grade: string;
  address: string;
}

// 定义路由参数的类型
type RootStackParamList = {
  Edit: { userData: UserData };
};

type Props = NativeStackScreenProps<RootStackParamList, 'Edit'>;

const Edit: React.FC = () => {
  const route = useRoute<Props['route']>();
  const navigation = useNavigation();
  const { userData } = route.params; // 从导航参数中获取 userData

  const [user, setUser] = useState<UserData>(userData); // 初始化状态为传递过来的用户数据

  const handleUpdate = async () => {
    try {
      const response = await axios.post('http://172.20.10.3:3000/cyw/updatepi', { ...user, _id: user._id });
      if (response.data.code === 200) {
        Alert.alert('Success', '修改成功');
        setTimeout(() => {
          navigation.goBack(); // 返回上一页
        }, 1000); // 一秒后自动关闭
      }
    } catch (error) {
      console.error('Error updating user data:', error);
      Alert.alert('Error', '修改失败');
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity 
          style={styles.backButton}
          onPress={() => navigation.goBack()}
        >
          <Text style={styles.backButtonText}>←</Text>
        </TouchableOpacity>
        <Text style={styles.headerTitle}>编辑资料</Text>
      </View>

      <View style={styles.content}>
        <View style={styles.row}>
          <Text style={styles.label}>头像</Text>
          <Image style={styles.avatar} source={{ uri: user.img }} />
        </View>
        <View style={styles.row}>
          <Text style={styles.label}>昵称</Text>
          <TextInput
            style={styles.input}
            value={user.name}
            onChangeText={(text) => setUser({ ...user, name: text })}
          />
        </View>
        <View style={styles.row}>
          <Text style={styles.label}>个人简介</Text>
          <TextInput
            style={styles.input}
            value={user.profile}
            onChangeText={(text) => setUser({ ...user, profile: text })}
          />
        </View>
        <View style={styles.row}>
          <Text style={styles.label}>年级</Text>
          <TextInput
            style={styles.input}
            value={user.grade}
            onChangeText={(text) => setUser({ ...user, grade: text })}
          />
        </View>
        <View style={styles.row}>
          <Text style={styles.label}>学校</Text>
          <TextInput
            style={styles.input}
            value={user.address}
            onChangeText={(text) => setUser({ ...user, address: text })}
          />
        </View>
        <TouchableOpacity style={styles.button} onPress={handleUpdate}>
          <Text style={styles.buttonText}>保存修改</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#F7F9FA',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 20,
    position: 'relative',
    width: '100%',
    height: 55,
  },
  backButton: {
    padding: 10,
    position: 'absolute',
    left: 0,
    zIndex: 1,
  },
  backButtonText: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  headerTitle: {
    flex: 1,
    fontSize: 20,
    fontWeight: 'bold',
    textAlign: 'center',
    marginLeft: 40,
    marginRight: 40,
  },
  content: {
    flex: 1,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 15,
  },
  label: {
    width: 80,
    fontSize: 16,
    color: '#333',
  },
  avatar: {
    width: 50,
    height: 50,
    borderRadius: 25,
  },
  input: {
    flex: 1,
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 5,
    padding: 10,
    backgroundColor: '#fff',
  },
  button: {
    marginTop: 20,
    backgroundColor: '#007AFF',
    padding: 15,
    borderRadius: 5,
    alignItems: 'center',
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
  },
});

export default Edit;